package studiodiva.portfolio.client.lib.view;

import static com.google.gwt.query.client.GQuery.$;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.query.client.css.CSS;
import com.google.gwt.query.client.css.Length;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class Layout {
  
  public static void center(final Widget widget) {
    final Element widgetClone = (Element) widget.getElement().cloneNode(true);
    $(widgetClone).show();
    $(widgetClone).css(CSS.POSITION.with(Position.ABSOLUTE));
    $(widgetClone).css(CSS.LEFT.with(Length.px(-3000)));
    $(widgetClone).css(CSS.TOP.with(Length.px(-3000)));
    Document.get().getBody().appendChild(widgetClone);

    $(widget).hide();
    $(widget).css("margin", "0px auto");
    View.doLaterOnAttached(widget, 0, new Runnable() {
      public void run() {
        $(widget).width($(widgetClone).outerWidth(true) + 3);
        $(widget).fadeIn();
        Document.get().getBody().removeChild(widgetClone);
      }
    });
  }

  public static void heightAsParent(IsWidget isWidget) {
    heightAsParent(isWidget.asWidget());
  }

  public static void heightAsParent(final Widget widget) {
    $(widget).hide();
    View.doLaterOnAttached(widget, 0, new Runnable() {
      public void run() {
        $(widget).height($(widget).parent().height());
        $(widget).fadeIn();
      }
    });
    Window.addResizeHandler(new ResizeHandler() {
      public void onResize(ResizeEvent event) {
        $(widget).height($(widget).parent().height());
      }
    });
  }
}
